package com.eat.servicebase.Interceptor;


import com.eat.common_utils.JwtUtils;
import com.eat.common_utils.R;
import com.eat.common_utils.ResponseUtil;
import com.eat.common_utils.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CZF
 * @create 2022-03-20 18:53
 */

//自定义token请求拦截器，拦截是否有token
@Slf4j
@Component   //加入spring容器中，因为使用到spring容器中的redisTemplate
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            System.out.println("OPTIONS请求，放行");
            return true;
        }


        log.info("token拦截器拦截的请求的地址为："+request.getRequestURL());
        //放行获取图片请求
        if (request.getRequestURL().indexOf("getPic") != -1) {
            return true;
        }

        System.out.println(redisTemplate);
        /**
         * 验证token
         */
        boolean isValid = JwtUtils.checkTokenByRequest(request,redisTemplate);

        if(isValid){
            log.info("认证成功");
            return true;
        }else {
            log.info("token不正确！认证失败");
            //返回响应，告诉前端认证失败
            ResponseUtil.out(request,response, R.error().code(ResultCode.AUTHENTICATION_FAILED).message("认证失败！"));

            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
